package cn.net.springboot.netty.http_demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Chris
 * @version 1.0.0
 * @date 2019/05/15
 * @since 1.0.0
 */
@Slf4j
public class HttpServer {
    public static void openServer(int port) {

        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup work = new NioEventLoopGroup(8);

        ServerBootstrap bootstrap = new ServerBootstrap();
        // bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.group(boss, work)
                // tcp/ip
                .channel(NioServerSocketChannel.class)
                // udp
                // .channel(NioDatagramChannel.class)
                // .option(ChannelOption.SO_BROADCAST, true)
                // .handler(new ChannelInitializer<NioSocketChannel>() {
                //     @Override
                //     protected void initChannel(NioSocketChannel ch) throws Exception {
                //
                //     }
                // })
                // .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator())
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // http request 报文解码

                        ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                        // 请求聚合
                        // ch.pipeline().addLast("http", new HttpObjectAggregator(65536));
                        // http response 报文编码
                        ch.pipeline().addLast("http-response-encode", new HttpResponseEncoder());
                        // 业务处理
                        ch.pipeline().addLast("http-servlet", new HttpServletHandler());
                    }
                });
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("服务已启动：" + port);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }

    }

    private static class HttpServletHandler extends SimpleChannelInboundHandler {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            // io.netty.channel.DefaultChannelHandlerContext
            System.out.println(ctx.getClass().getName());
            // io.netty.handler.codec.http.DefaultHttpRequest io.netty.handler.codec.http.LastHttpContent$1
            System.out.println(msg.getClass().getName());
            // 业务处理
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");
            response.content().writeBytes("hello luban is a good man".getBytes());

            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

            ChannelFuture future = ctx.channel().writeAndFlush(msg);
            future.addListener((ChannelFutureListener) channelFuture ->
                    log.info("服务端手动发送 Google Protocol 成功={}", msg));
        }
    }

    public static void main(String[] args) {
        HttpServer.openServer(9088);
    }

}
